<template>
  <div id="add_role_id">
    <el-dialog
      :title="form.id != 0 ? '修改用户' : '创建用户'"
      :visible.sync="isShow.sta"
      width="50%"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        style="text-align: left"
      >
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="form.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree
            :data="MenuList"
            show-checkbox
            node-key="id"
            :default-checked-keys="checked_keys"
            :props="defaultProps"
            ref="addR"
          ></el-tree>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="quxiao">取 消</el-button>
        <el-button type="primary" @click="sumbit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      form: {
        id: 0,
        rolename: "",
        status: 1,
      },
      defaultProps: {
        children: "children",
        label: "title",
      },
      checked_keys: [],
    };
  },
  created() {
    this.MenuActions();
  },
  computed: {
    ...mapState({ MenuList: (state) => state.MenuStore.MenuList }),
  },
  methods: {
    xiugaishujus(obj) {
      console.log(obj);
      let menuss = obj.menus;
      this.checked_keys = menuss.split(",");
      this.form.rolename = obj.rolename;
      this.form.id = obj.id;
      this.form.status = obj.status;
    },
    sumbit() {
      let menus = this.$refs.addR.getCheckedKeys().join(",");
      let shuju = {
        ...this.form,
        menus,
      };
      let url = "";
      if (shuju.id == 0) {
        url = "/api/roleadd";
      } else {
        url = "/api/roleedit";
      }
      //  把数据存放在数据库中(调用接口)
      this.$http.post(url, shuju).then((res) => {
        // 可以获取到添加成功字段
        // console.log(res);
        // 判断res的添加状态等于200的时候判断
        if (res.code == 200) {
          // 当模态框消失
          this.isShow.sta = false;
          // 清空当前数据
          this.form = {
            id: 0,
            rolename: "",
            status: 1,
          };
          this.$refs.addR.setCheckedKeys([]);
          //用父子传参让页面数据进行重新加载
          this.$emit("chongqi");
        }
      });
    },
    quxiao() {
      this.isShow.sta = false;
      this.form = {
        id: 0,
        rolename: "",
        status: 1,
      };
      this.$refs.addR.setCheckedKeys([]);
    },
    ...mapActions("MenuStore", ["MenuActions"]),
  },
  props: ["isShow"],
};
</script>

<style>
</style>